#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include <ctime>

#define SOCKET_PORT 6600
#define MAXLINE 512*512+32
#define MAXBAGSIEZ 1024

char  sendline[MAXLINE];
int sendLenth=0;
pthread_mutex_t socketDataLock;

typedef unsigned int useconds_t;
inline int usleep(useconds_t us) {
    struct timespec req;
    req.tv_sec  = (long) (us / 1000000U);
    req.tv_nsec = (long)((us % 1000000U)*1000U);
    int status = nanosleep(&req,0);
    return status ? -1 : 0;
}

void* socketSendThread(void* IP_Add)
{
    int   sockfd, n;
    pthread_mutex_init(&socketDataLock,NULL);
    struct sockaddr_in  servaddr;
    std::string add((char*)IP_Add);

    while(1)
    {
        if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
            printf("create socket error: %s(errno: %d)\n", strerror(errno),errno);
            return 0;
        }

        memset(&servaddr, 0, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(SOCKET_PORT);
        if( inet_pton(AF_INET, add.c_str(), &servaddr.sin_addr) <= 0){
            printf("inet_pton error for %s\n",add.c_str());
            return 0;
        }

        if( connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0){
            printf("connect error: %s(errno: %d)\n",strerror(errno),errno);
            return 0;
        }
        while(1)
        {
            int cnt=0;
            while(sendLenth!=0)
            {
                ssize_t tmp;
                pthread_mutex_lock(&socketDataLock);
                if(sendLenth>MAXBAGSIEZ){
                    tmp=send(sockfd, &sendline[cnt], MAXBAGSIEZ, 0);
                    sendLenth-=MAXBAGSIEZ;
                    cnt+=MAXBAGSIEZ;
                }
                else{
                    tmp=send(sockfd, &sendline[cnt], sendLenth, 0);
                    sendLenth=0;
                    cnt+=sendLenth;
                }
                pthread_mutex_unlock(&socketDataLock);
                if(tmp<0)
                {
                    // printf("Server closed the link!\n");
                    break;
                }
            }
            usleep(10000);//10ms
        }
        
        close(sockfd);
    }
    return 0;
}

int socketSendData(int8_t* data,int dataLen)
{
    if(dataLen==0) return 0;
    // if(pthread_mutex_trylock(&socketDataLock)!=0) return 0;
    pthread_mutex_lock(&socketDataLock);
    sendLenth=dataLen;
    memcpy(sendline,data,sendLenth);
    sendline[sendLenth]=0x55;
    pthread_mutex_unlock(&socketDataLock);
    return 1;
}
